import { loginApi, logoutApi, getInfoApi } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getExpiredTime,
  setExpiredTime,
  removeExpiredTime,
  setUserId,
  getUserId,
  removeUserId
} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    expiredTime: getExpiredTime(),
    userId: null,
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_EXPIRED_TIME: (state, time) => {
    state.expiredTime = time
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginApi({ username, password })
        .then(response => {
          if (response.success) {
            const { data } = response
            commit('SET_TOKEN', data.token)
            commit('SET_EXPIRED_TIME', data.expiredTime)
            commit('SET_USER_ID', data.userId)
            setToken(data.token)
            setExpiredTime(data.expiredTime)
            setUserId(data.userId)
            resolve()
            return
          }
          reject()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfoApi({
        userId: getUserId()
      })
        .then(response => {
          const { data } = response
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { name, avatar } = data
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logoutApi()
        .then(() => {
          removeToken() // must remove  token  first
          removeExpiredTime()
          removeUserId()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      removeExpiredTime()
      removeUserId()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
